import *as React from 'react'
import Nav from '../../components/nav'
import moment from 'moment'
import style from './style.module.less'
import { getPill } from '../../services/api'

function Open() {
  const [key,setKey]=React.useState('')
  const [flag,setFlag]=React.useState('')
  const [pill,setPill]=React.useState({
    name: '',
    email: '',
    time: '',
    content: '',
    tip: '',
    id:''})
  const [second,setSecond]=React.useState(0)
  React.useEffect(() => {
    if(second>0)
    setTimeout(() => {
      if (second  === 0)
        clearInterval()
      setSecond(second - 1)
    }, 1000)
  }, [second])
  const timeDiff = (time: string) => { 
    return moment(time).diff(moment().format("YYYY-MM-DD HH:mm:ss"), "seconds")
  }
  return (
    <>
      <Nav />
      <div className="container">
        <h1 className="page-header">打开胶囊</h1>
        <div className="main">
          <form method="post">
            <label>
              胶囊Key：
              <input name="key" className="key" type="text"
                value={key}
                onChange={(e) => setKey(e.target.value)}
              />
              <input type="button" id="openpill" value="打开胶囊"
                onClick={async () => {
                  if (key) {
                    let ifo = await getPill({'id':key})
                    console.log(ifo);
                    if (ifo.stat !== "not_found") {
                      setPill(Object(ifo))
                      setFlag("found")
                      let s = timeDiff(Object(ifo).time) - 1;
                      if (s > 0){
                        setSecond(s)
                      }
                    }else{
                      setFlag("not_found")
                    }
                  }
                }}
              />
            </label>
          </form>
          <div className={(flag === "not_found") ? (style.tips_highlight) : (style.closepill)}>没有这个胶囊Key</div>
          <div className={(flag==="found") ? (style.openpill) : (style.closepill)}>
            <h2 className={timeDiff(pill.time) > 0 ? (style.openpill) : (style.closepill)}>这颗胶囊未到提取时间，不能打开。</h2>
            <h2 className={timeDiff(pill.time) < 0 ? (style.openpill) : (style.closepill)}>{pill.name} 在 {pill.time} 想对你说：</h2>
            <span className={timeDiff(pill.time) > 0 ? (style.openpill) : (style.closepill)}>打开时间在 <b>{pill.time}</b>，距离现在 <b>{second}</b> 秒。</span>
            <div className={style.content}>
              <p className={timeDiff(pill.time) > 0 ? (style.openpill) : (style.closepill)}><b>{pill.name}</b> 给你留的提示信息：</p>
              <pre>{timeDiff(pill.time) < 0 ? (pill.content) : (pill.tip)}</pre>
            </div>
          </div>
        </div>
      </div>
    </>
  )
}
export default Open


